<template>
  <a-modal
    v-model:visible="visible"
    title="客户续费"
    :width="800"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
    >
             <a-form-item label="子合同名称/单位名称" name="subContractName">
         <a-input
           v-model:value="formData.subContractName"
           placeholder="子合同名称"
           disabled
         />
       </a-form-item>

<!--       <a-form-item label="子合同ID" name="subContractId">-->
<!--         <a-input-->
<!--           v-model:value="formData.subContractId"-->
<!--           placeholder="子合同ID"-->
<!--           disabled-->
<!--         />-->
<!--       </a-form-item>-->

       <a-form-item label="客户" name="customerName">
         <a-select
           v-model:value="formData.customerName"
           placeholder="请选择客户"
           :loading="customerLoading"
           show-search
           :filter-option="(input, option) => option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
           @change="handleCustomerChange"
           allow-clear
         >
           <a-select-option v-for="customer in customerOptions" :key="customer.id" :value="customer.customerName" :label="customer.customerName">
             {{ customer.customerName }}
           </a-select-option>
         </a-select>
       </a-form-item>

      <a-form-item label="续费金额" name="renewalAmount">
        <a-input-number
          v-model:value="formData.renewalAmount"
          placeholder="请输入续费金额"
          style="width: 100%"
          :min="0"
          :precision="2"
        />
      </a-form-item>

      <a-form-item label="合同主题" name="contractTheme">
        <a-input
          v-model:value="formData.contractTheme"
          placeholder="请输入合同主题"
          style="width: 100%"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="产品类型" name="productType">
        <a-select
          v-model:value="formData.productType"
          placeholder="请选择产品类型"
          :loading="productTypeLoading"
          @change="handleProductTypeChange"
          show-search
          :filter-option="(input, option) => option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
          allow-clear
        >
          <a-select-option v-for="type in productTypeList" :key="type.id" :value="type.id" :label="type.productType">
            {{ type.productType }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="产品内容" name="productNameIds">
        <a-select
          v-model:value="formData.productNameIds"
          mode="multiple"
          placeholder="请选择产品内容（可多选）"
          :loading="productNameLoading"
          @change="handleProductNameChange"
          :disabled="!formData.productType"
          show-search
          :filter-option="(input, option) => option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
          :max-tag-count="2"
          :max-tag-text-length="10"
          allow-clear
        >
          <a-select-option v-for="product in productNameList" :key="product.id" :value="product.id" :label="product.productName">
            {{ product.productName }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { 
  getCustomerNameAndId, 
  getProductTypes, 
  getProductNameByTypeId, 
  backContracts 
} from '../AfterSales.api';

const { createMessage } = useMessage();

// 模态框状态
const visible = ref(false);
const confirmLoading = ref(false);
const formRef = ref();

// 表单数据
const formData = reactive({
  customerName: '',
  customerId: '',
  renewalAmount: undefined,
  contractTheme: '', // 合同主题
  productType: '',
  productTypeName: '',
  productNameIds: [],
  productName: [],
  subContractId: '', // 子合同ID
  subContractName: '', // 子合同名称
});

// 表单验证规则
const rules = {
  customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
  renewalAmount: [{ required: true, message: '请输入续费金额', trigger: 'blur' }],
  contractTheme: [{ required: true, message: '请输入合同主题', trigger: 'blur' }],
  productType: [{ required: true, message: '请选择产品类型', trigger: 'change' }],
  productNameIds: [{ required: true, message: '请选择产品内容', trigger: 'change' }],
};

// 选项数据
const customerOptions = ref([]);
const productTypeList = ref([]);
const productNameList = ref([]);

// 加载状态
const customerLoading = ref(false);
const productTypeLoading = ref(false);
const productNameLoading = ref(false);

// 获取客户列表
const fetchCustomers = async () => {
  try {
    customerLoading.value = true;
    const res = await getCustomerNameAndId();
    if (res) {
      customerOptions.value = res;
    } else {
      customerOptions.value = [];
    }
  } catch (error) {
    console.error('获取客户列表失败:', error);
    createMessage.error('获取客户列表失败');
    customerOptions.value = [];
  } finally {
    customerLoading.value = false;
  }
};

// 获取产品类型列表
const fetchProductTypes = async () => {
  try {
    productTypeLoading.value = true;
    const res = await getProductTypes();
    if (res) {
      productTypeList.value = res;
    } else {
      productTypeList.value = [];
    }
  } catch (error) {
    console.error('获取产品类型失败:', error);
    createMessage.error('获取产品类型失败');
    productTypeList.value = [];
  } finally {
    productTypeLoading.value = false;
  }
};

// 根据产品类型ID获取产品名称列表
const fetchProductName = async (productTypeId) => {
  if (!productTypeId) {
    productNameList.value = [];
    return;
  }

  try {
    productNameLoading.value = true;
    const res = await getProductNameByTypeId(productTypeId);
    if (res) {
      productNameList.value = res;
    } else {
      productNameList.value = [];
    }
  } catch (error) {
    console.error('获取产品名称失败:', error);
    createMessage.error('获取产品名称失败');
    productNameList.value = [];
  } finally {
    productNameLoading.value = false;
  }
};

// 客户选择变化处理
const handleCustomerChange = (value) => {
  if (value) {
    const selectedCustomer = customerOptions.value.find(customer => customer.customerName === value);
    if (selectedCustomer) {
      formData.customerId = selectedCustomer.id;
    }
  } else {
    formData.customerId = '';
  }
};

// 产品类型选择变化处理
const handleProductTypeChange = (value) => {
  // 清空产品名称列表
  formData.productNameIds = [];
  formData.productName = [];

  // 如果选中了产品类型，获取对应的产品名称
  if (value) {
    const selectedType = productTypeList.value.find(item => item.id === value);
    if (selectedType) {
      formData.productType = selectedType.id;
      formData.productTypeName = selectedType.productType;
      fetchProductName(selectedType.id);
    }
  } else {
    productNameList.value = [];
  }
};

// 产品名称选择变化处理（多选）
const handleProductNameChange = (values) => {
  if (values && values.length > 0) {
    // 根据选中的ID获取对应的产品名称
    const selectedProducts = productNameList.value.filter(item => values.includes(item.id));
    const productName = selectedProducts.map(item => item.productName);

    formData.productNameIds = values;
    formData.productName = productName;
  } else {
    formData.productNameIds = [];
    formData.productName = [];
  }
};

// 打开模态框
const open = (selectedRecord) => {
  visible.value = true;
  // 重置表单
  Object.assign(formData, {
    customerName: '',
    customerId: '',
    renewalAmount: undefined,
    contractTheme: '', // 重置合同主题
    productType: '',
    productTypeName: '',
    productNameIds: [],
    productName: [],
    subContractId: selectedRecord?.subContractId || '', // 设置子合同ID
    subContractName: selectedRecord?.subContractName || '', // 设置子合同名称
  });
  // 加载数据
  fetchCustomers();
  fetchProductTypes();
};

// 确认按钮
const handleOk = async () => {
  try {
    await formRef.value.validate();
    confirmLoading.value = true;

    // 准备提交数据
    const submitData = {
      customerName: formData.customerName,
      customerId: formData.customerId,
      renewalAmount: formData.renewalAmount,
      contractTheme: formData.contractTheme, // 添加合同主题
      productType: formData.productType,
      productTypeName: formData.productTypeName,
      productNameIds: formData.productNameIds,
      productName: formData.productName,
      subContractId: formData.subContractId, // 添加子合同ID
      subContractName: formData.subContractName, // 添加子合同名称
    };

    const res = await backContracts(submitData);
    if (res && res.success) {
      createMessage.success('客户续费成功');
      handleCancel();
      // 触发成功回调
      emit('success');
    } else {
      createMessage.error(res?.message || '客户续费失败');
    }
  } catch (error) {
    console.error('客户续费失败:', error);
    createMessage.error('客户续费失败');
  } finally {
    confirmLoading.value = false;
  }
};

// 取消按钮
const handleCancel = () => {
  visible.value = false;
  formRef.value?.resetFields();
};

// 定义事件
const emit = defineEmits(['success']);

// 暴露方法
defineExpose({
  open,
});
</script>

<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 16px;
}
</style>
